package cn.iocoder.yudao.module.pay.service.order;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * 延迟任务
 *
 * @author ε3
 * @date 2025/3/10
 */
public class DelayedTask implements Delayed {

    private final Runnable task;
    private final long startTime;

    public DelayedTask(Runnable task, long delayInMilliseconds) {
        this.task = task;
        this.startTime = System.currentTimeMillis() + delayInMilliseconds;
    }

    @Override
    public long getDelay(TimeUnit unit) {
        long diff = startTime - System.currentTimeMillis();
        return unit.convert(diff, TimeUnit.MILLISECONDS);
    }

    @Override
    public int compareTo(Delayed other) {
        return Long.compare(this.startTime, ((DelayedTask) other).startTime);
    }

    public void run() {
        task.run();
    }
}
